package com.banmao.mall.service.client.impl;

import com.banmao.mall.mapper.*;
import com.banmao.mall.model.bo.client.order.OrderSubmitBO;
import com.banmao.mall.model.pojo.*;
import com.banmao.mall.model.vo.admin.goods.GoodsVO;
import com.banmao.mall.model.vo.client.order.detail.OrderDetailsVO;
import com.banmao.mall.model.vo.client.order.footprint.FootPrintVO;
import com.banmao.mall.model.vo.client.order.footprint.FootprintListBean;
import com.banmao.mall.model.vo.client.order.nopayment.DataBean;
import com.banmao.mall.model.vo.client.order.nopayment.GoodsListBean;
import com.banmao.mall.model.vo.client.order.nopayment.HandleOptionBean;
import com.banmao.mall.model.vo.client.order.nopayment.NoPaymentVO;
import com.banmao.mall.service.client.OrderService;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderGoodsMapper orderGoodsMapper;
    @Autowired
    CommentMapper commentMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    FoorprintMapper foorprintMapper;
    @Autowired
    UserMapper userMapper;
    @Autowired
    FeedbackMapper feedbackMapper;
    @Autowired
    AddressMapper addressMapper;
    @Autowired
    CartMapper cartMapper;
    @Autowired
    CouponMapper couponMapper;
    @Autowired
    GrouponRulesMapper grouponRulesMapper;
    @Autowired
    RegionMapper regionMapper;
    @Autowired
    SystemMapper systemMapper;
    @Autowired
    GoodsProductMapper goodsProductMapper;
    @Autowired
    CouponUserMapper couponUserMapper;
    @Override
    public NoPaymentVO selectNoPaymentList(Integer showType, Integer page, Integer size) {
        NoPaymentVO paymentVO = new NoPaymentVO();
        Session session = SecurityUtils.getSubject().getSession();
        Integer userId = (Integer) session.getAttribute("userId");
        Integer orderStatus = null;
        if(showType ==0){
            orderStatus = null;
        }
        if(showType==1){
            //未付款
            orderStatus = 101;
        }
        if(showType==2){
            orderStatus = 201;
        }
        if(showType==3){
            orderStatus = 301;
        }
        if(showType==4){
            orderStatus = 401;
        }
        //未付款

        Integer count = orderMapper.selectCount(userId,orderStatus);
        paymentVO.setCount(count);

        paymentVO.setTotalPages((count/size)+1);
        //
        List<DataBean> goodsList = orderMapper.selectDataBeanList(userId,orderStatus);
        for (DataBean dataBean : goodsList) {
//            if(showType==0){
//                dataBean.setOrderStatusText("全部");
//            }

            Short orderStatus1 = dataBean.getOrderStatus();
            if(orderStatus1==101){
                dataBean.setOrderStatusText("未付款");
            }
            if(orderStatus1==201){
                dataBean.setOrderStatusText("未发货");
            }
            if(orderStatus1==301){
                dataBean.setOrderStatusText("未收货");
            }
            if(orderStatus1==401){
                dataBean.setOrderStatusText("未评价");
            }
            if(orderStatus1==102){
                dataBean.setOrderStatusText("用户已取消");
            }
            if(orderStatus1==103){
                dataBean.setOrderStatusText("系统取消");
            }
            if(orderStatus1==202){
                dataBean.setOrderStatusText("申请退款");
            }
            if(orderStatus1==203){
                dataBean.setOrderStatusText("已退款");
            }
            if(orderStatus1==402){
                dataBean.setOrderStatusText("系统收货");
            }
            if(orderStatus1==501){
                dataBean.setOrderStatusText("已评价");
            }
            //预留
            dataBean.setIsGroupin(false);
            Integer orderId = dataBean.getId();
            List<GoodsListBean> listBeans = orderMapper.selectGoodsList(orderId);
            dataBean.setGoodsList(listBeans);
            HandleOptionBean handleOptionBean = getHandleOptionBean(orderStatus1);
//            HandleOptionBean handleOptionBean = new HandleOptionBean();
//            handleOptionBean.setCancel(true);
//            handleOptionBean.setPay(true);
//            handleOptionBean.setDelete(false);
//            handleOptionBean.setComment(false);
//            handleOptionBean.setConfirm(false);
//            handleOptionBean.setRefund(false);
//            handleOptionBean.setRebuy(false);
            dataBean.setHandleOption(handleOptionBean);

        }
        paymentVO.setData(goodsList);
        return paymentVO;
    }

    @Override
    public OrderDetailsVO selectOrderDetails(Integer orderId) {
        OrderDetailsVO orderDetailsVO = new OrderDetailsVO();
        Order order = orderMapper.selectByPrimaryKey(orderId);
        Short orderStatus = order.getOrderStatus();
        HandleOptionBean handleOptionBean = getHandleOptionBean(orderStatus);
        order.setHandleOption(handleOptionBean);
        orderDetailsVO.setOrderInfo(order);

        List<OrderGoods> list = orderGoodsMapper.selectByOrderId(orderId);
        orderDetailsVO.setOrderGoods(list);
        return orderDetailsVO;
    }

    @Override
    public void updateOrderPrepay(Integer orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setOrderStatus((short)201);
        order.setUpdateTime(new Date());
        order.setPayTime(new Date());
        orderMapper.updateByPrimaryKey(order);

        List<OrderGoods> list = orderGoodsMapper.selectByOrderId(orderId);
        for (OrderGoods orderGoods : list) {
            Integer productId = orderGoods.getProductId();
            GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(productId);
            Short number = orderGoods.getNumber();
            Integer number1 = goodsProduct.getNumber();
            goodsProduct.setNumber(number1-number);
            goodsProduct.setUpdateTime(new Date());
            goodsProductMapper.updateByPrimaryKey(goodsProduct);

        }
    }

    @Override
    public void cancelOrderPrepay(Integer orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setOrderStatus((short)102);
        order.setUpdateTime(new Date());

        orderMapper.updateByPrimaryKey(order);

        List<OrderGoods> list = orderGoodsMapper.selectByOrderId(orderId);
        for (OrderGoods orderGoods : list) {
            Integer productId = orderGoods.getProductId();
            GoodsProduct goodsProduct = goodsProductMapper.selectByPrimaryKey(productId);
            Short number = orderGoods.getNumber();
            Integer number1 = goodsProduct.getNumber();
            goodsProduct.setNumber(number1-number);
            goodsProduct.setUpdateTime(new Date());
            goodsProductMapper.updateByPrimaryKey(goodsProduct);

            orderGoods.setDeleted(true);
            orderGoods.setUpdateTime(new Date());
            orderGoodsMapper.updateByPrimaryKey(orderGoods);
        }
    }

    @Override
    public void insertOrderComment(Comment comment) {

        Integer orderGoodsId = comment.getOrderGoodsId();
        comment.setValueId(orderGoodsId);
        comment.setAddTime(new Date());
        comment.setUpdateTime(new Date());
        String[] picUrls = comment.getPicUrls();
        for(int i=0;i<picUrls.length;i++){
            String relaUrl = getRelaUrl(picUrls[i]);
            picUrls[i] = relaUrl;
        }
        comment.setPicUrls(picUrls);
        comment.setType((byte)0);
        comment.setDeleted(false);
        Integer userId = (Integer) SecurityUtils.getSubject().getSession().getAttribute("userId");
        comment.setUserId(userId);
        commentMapper.insert(comment);

    }

    @Override
    public Goods selectOrderGoods(Integer orderId,Integer goodsId) {
        Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
        String picUrl = goods.getPicUrl();
        getRelaUrl(picUrl);
        goods.setPicUrl(picUrl);

        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setOrderStatus((short)501);
        order.setUpdateTime(new Date());
        orderMapper.updateByPrimaryKey(order);

        return goods;
    }

    @Override
    public void updateOrderConfirm(Integer orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setOrderStatus((short)401);
        order.setUpdateTime(new Date());
        order.setConfirmTime(new Date());
        orderMapper.updateByPrimaryKey(order);
    }

    @Override
    public void updateOrderDeleted(Integer orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setUpdateTime(new Date());
        order.setDeleted(true);
        orderMapper.updateByPrimaryKey(order);
    }
    //退款
    @Override
    public void updateOrderRefund(Integer orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        order.setUpdateTime(new Date());
        order.setOrderStatus((short)203);
        orderMapper.updateByPrimaryKey(order);
    }

    @Override
    public FootPrintVO selectFootprintList(Integer page, Integer size) {
        FootPrintVO footPrintVO = new FootPrintVO();
        Integer userId = (Integer) SecurityUtils.getSubject().getSession().getAttribute("userId");
        List<FootprintListBean> list = foorprintMapper.selectFootPrintList(userId,(page-1)*size,size);
        for (FootprintListBean footprintListBean : list) {
            Integer goodsId = footprintListBean.getGoodsId();
            GoodsVO goodsVO = goodsMapper.selectByGoodsID(goodsId);
            footprintListBean.setBrief(goodsVO.getBrief());
            footprintListBean.setPicUrl(goodsVO.getPicUrl());
            footprintListBean.setName(goodsVO.getName());
            footprintListBean.setRetailPrice(goodsVO.getRetailPrice());
        }
        footPrintVO.setFootprintList(list);
        Integer total = foorprintMapper.setCountTotal(userId);
        footPrintVO.setTotalPages((total/size)+1);
        return footPrintVO;
    }

    @Override
    public void insertFeedbackSumbit(Feedback feedback) {
        Integer userId = (Integer) SecurityUtils.getSubject().getSession().getAttribute("userId");
        feedback.setAddTime(new Date());
        feedback.setDeleted(false);
        feedback.setStatus(0);
        feedback.setUpdateTime(new Date());
        feedback.setUserId(userId);
        User user = userMapper.selectByPrimaryKey(userId);
        String username = user.getUsername();
        feedback.setUsername(username);
        feedbackMapper.insert(feedback);
    }

    @Override
    public Integer insertOrderSubmit(OrderSubmitBO orderSubmitBO) {
        Address address = addressMapper.selectByPrimaryKey(orderSubmitBO.getAddressId());

        Cart cart = cartMapper.selectByPrimaryKey(orderSubmitBO.getCartId());
        Integer orderId = -1;
        //优惠卷
        if(cart!=null){
            Order order = this.method(orderSubmitBO, cart);
            Integer cartId = cart.getId();
            cart.setDeleted(true);
            cartMapper.updateByPrimaryKey(cart);
            Integer orderId1 = order.getId();
            orderId = orderId1;

        }else {
            Integer userId = address.getUserId();
            List<Cart> carts = cartMapper.selectByUserId(userId);
            for (Cart cart1 : carts) {
                Order method = this.method(orderSubmitBO, cart1);
                Integer id = method.getId();
                orderId = id;
                cart1.setDeleted(true);
                cartMapper.updateByPrimaryKey(cart1);
            }
        }
        return orderId;
    }


    private Order method(OrderSubmitBO orderSubmitBO, Cart cart){
        Address address = addressMapper.selectByPrimaryKey(orderSubmitBO.getAddressId());
        Coupon coupon = couponMapper.selectByPrimaryKey(orderSubmitBO.getCouponId());
        GrouponRules grouponRules = grouponRulesMapper.selectByPrimaryKey(orderSubmitBO.getGrouponRulesId());

        Integer provinceId = address.getProvinceId();
        Region region = regionMapper.selectByPrimaryKey(provinceId);
        String provinceName = region.getName();//湖北省

        Integer cityId = address.getCityId();
        Region region1 = regionMapper.selectByPrimaryKey(cityId);
        String cityName = region1.getName();

        Integer areaId = address.getAreaId();
        Region region2 = regionMapper.selectByPrimaryKey(areaId);
        String areaName = region2.getName();
        String addressName = provinceName+" "+cityName+" "+areaName+" "+address.getAddress();

        Integer freightValue = 8;
        int freight_min = 88;

        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd-hh-mm-ss");
        String format = ft.format(new Date());
        String replace = format.replace("-", "");
        Order order = new Order();

        order.setUserId(cart.getUserId());
        order.setOrderSn(replace);
        order.setOrderStatus((short)101);
        order.setConsignee(address.getName());
        order.setMobile(address.getMobile());
        order.setAddress(addressName);
        order.setMessage(orderSubmitBO.getMessage());
        order.setGoodsPrice(cart.getPrice());
        order.setIntegralPrice(new BigDecimal(0));
        order.setGrouponPrice(new BigDecimal(0));
        Integer singlePrice = cart.getPrice().intValue();
        Integer number = Integer.parseInt(String.valueOf(cart.getNumber()));
        int orderPrice = singlePrice*number;
        if(orderPrice>freight_min){
            order.setFreightPrice(new BigDecimal(0.00));
            order.setOrderPrice(new BigDecimal(orderPrice));

            if(coupon!=null){
                int discount = coupon.getDiscount().intValue();// 减多少钱//-15
                int min = coupon.getMin().intValue();//优惠卷使用的低价//99
                if(orderPrice>min){
                    order.setActualPrice(new BigDecimal(orderPrice-discount));
                    order.setCouponPrice(new BigDecimal(discount));
                }else{
                    order.setActualPrice(new BigDecimal(orderPrice));
                    order.setCouponPrice(new BigDecimal(0));
                }
            }else{
                order.setActualPrice(new BigDecimal(orderPrice));
                order.setCouponPrice(new BigDecimal(0));
            }

        }else{
            order.setFreightPrice(new BigDecimal(8.00));
            order.setOrderPrice(new BigDecimal(orderPrice+8));
            if(coupon!=null){
                int discount = coupon.getDiscount().intValue();// 减多少钱//-15
                int min = coupon.getMin().intValue();//优惠卷使用的低价//99
                if(orderPrice>min){
                    order.setActualPrice(new BigDecimal(orderPrice+8-discount));
                    order.setCouponPrice(new BigDecimal(discount));
                }else{
                    order.setActualPrice(new BigDecimal(orderPrice+8));
                    order.setCouponPrice(new BigDecimal(0));
                }
            }else{
                order.setActualPrice(new BigDecimal(orderPrice+8));
                order.setCouponPrice(new BigDecimal(0));
            }

        }
        order.setAddTime(new Date());
        order.setUpdateTime(new Date());
        order.setDeleted(false);
        orderMapper.insert(order);
        Integer orderId = order.getId();
        Integer userId = cart.getUserId();
        short status = 0;
        if(coupon!=null){
            Integer couponId = coupon.getId();
            List<CouponUser> list = couponUserMapper.selectList(userId,couponId,(short) 0);
            if(list.size()>0){
                Short statusTrue = 1;
                CouponUser couponUser = list.get(0);
                couponUser.setStatus(statusTrue);
                couponUser.setUsedTime(new Date());
                couponUser.setOrderId(orderId);
                couponUser.setUpdateTime(new Date());
                couponUserMapper.updateByPrimaryKey(couponUser);
            }

            cart.setDeleted(true);
            cartMapper.updateByPrimaryKey(cart);
        }
        OrderGoods orderGoods = new OrderGoods();
        orderGoods.setOrderId(orderId);
        orderGoods.setGoodsId(cart.getGoodsId());
        orderGoods.setGoodsName(cart.getGoodsName());
        orderGoods.setGoodsSn(cart.getGoodsSn());
        orderGoods.setProductId(cart.getProductId());
        orderGoods.setNumber(cart.getNumber());
        orderGoods.setPrice(cart.getPrice());
        orderGoods.setSpecifications(cart.getSpecifications());
        orderGoods.setPicUrl(cart.getPicUrl());
        orderGoods.setComment(0);
        orderGoods.setAddTime(new Date());
        orderGoods.setUpdateTime(new Date());
        orderGoods.setDeleted(false);
        orderGoodsMapper.insert(orderGoods);
        return order;
    }

    public static String getRelaUrl(String url){
        String replace = url;
        if(url!=null&&url.contains("http://localhost:8083")){
            replace = url.replace("http://localhost:8083", "");
        }
        return replace;
    }
    public static HandleOptionBean getHandleOptionBean(Short orderStatus){
        HandleOptionBean handleOptionBean = new HandleOptionBean();
        if(orderStatus==101){
//            dataBean.setOrderStatusText("未付款");
            handleOptionBean.setCancel(true);
            handleOptionBean.setPay(true);
            handleOptionBean.setDelete(false);
            handleOptionBean.setComment(false);
            handleOptionBean.setConfirm(false);
            handleOptionBean.setRefund(false);
            handleOptionBean.setRebuy(false);
        }
        if(orderStatus==201){
//            dataBean.setOrderStatusText("未发货");
            handleOptionBean.setCancel(true);
            handleOptionBean.setPay(false);
            handleOptionBean.setDelete(false);
            handleOptionBean.setComment(false);
            handleOptionBean.setConfirm(false);
            handleOptionBean.setRefund(false);
            handleOptionBean.setRebuy(false);
        }
        if(orderStatus==301){
//            dataBean.setOrderStatusText("未收货");
            handleOptionBean.setCancel(false);
            handleOptionBean.setPay(false);
            handleOptionBean.setDelete(true);
            handleOptionBean.setComment(true);
            handleOptionBean.setConfirm(true);
            handleOptionBean.setRefund(false);
            handleOptionBean.setRebuy(true);
        }
        if(orderStatus==401){
//            dataBean.setOrderStatusText("未评价");
            //"handleOption": {
            //				"cancel": false,
            //				"delete": true,
            //				"pay": false,
            //				"comment": true,
            //				"confirm": false,
            //				"refund": false,
            //				"rebuy": true
            //			}
            handleOptionBean.setCancel(false);
            handleOptionBean.setPay(false);
            handleOptionBean.setDelete(true);
            handleOptionBean.setComment(true);
            handleOptionBean.setConfirm(true);
            handleOptionBean.setRefund(true);
            handleOptionBean.setRebuy(true);
        }
        if(orderStatus==102){
//            dataBean.setOrderStatusText("用户取消");
        }
        if(orderStatus==103){
//            dataBean.setOrderStatusText("系统取消");
//            "cancel": false,
//                    "delete": true,
//                    "pay": false,
//                    "comment": false,
//                    "confirm": false,
//                    "refund": false,
//                    "rebuy": false
            handleOptionBean.setCancel(false);
            handleOptionBean.setPay(false);
            handleOptionBean.setDelete(true);
            handleOptionBean.setComment(false);
            handleOptionBean.setConfirm(false);
            handleOptionBean.setRefund(false);
            handleOptionBean.setRebuy(false);
        }
        if(orderStatus==202){
//            dataBean.setOrderStatusText("申请退款");
        }
        if(orderStatus==203){
//            dataBean.setOrderStatusText("已退款");
        }
        if(orderStatus==402){
//            dataBean.setOrderStatusText("系统收货");
        }

        return handleOptionBean;
    }
}
